package cn.singno.springBoot.demo.ch16_mvc;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.propertyeditors.CustomBooleanEditor;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class ControllerGlobalHandler {

	@ExceptionHandler(Exception.class)
	public ModelAndView exception(Exception excetion) {
		ModelAndView modelAndView = new ModelAndView("error");
		modelAndView.addObject("errorMessage", excetion.getMessage());
		return modelAndView;
	}

	@ModelAttribute
	public void addAttributes(Model model) {
		model.addAttribute("msg", "额外信息");
	}

	@InitBinder
	public void initBinder(WebDataBinder webDataBinder) {
		webDataBinder.setDisallowedFields("id");

		DateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd");
		CustomDateEditor customDateEditor = new CustomDateEditor(dateFormat, true);
//		CustomBooleanEditor CustomBooleanEditor = new CustomBooleanEditor("1", "0", Boolean.TRUE);
		
		webDataBinder.registerCustomEditor(Date.class, customDateEditor);
//		webDataBinder.registerCustomEditor(Boolean.class, CustomBooleanEditor);
	}
}
